package com.itheima.service.impl;

import com.itheima.dto.UserLoginDTO;
import com.itheima.entity.SysUser;
import com.itheima.mapper.SysUserMapper;
import com.itheima.service.IndexService;
import com.itheima.util.IpUtils;
import com.itheima.util.JwtUtils;
import com.itheima.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * @ClassName : IndexServiceImpl
 * @Description : 登录1.0
 * @Author : tao
 * @Date: 2023-09-19 15:33
 */
@Service
@RequiredArgsConstructor
public class IndexServiceImpl implements IndexService {
    //调用 mapper 操作数据
    private final SysUserMapper sysUserMapper;
    //调用工具类
    private final IpUtils ipUtils;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //查找名字
        SysUser sysUser = sysUserMapper.selectUserByLoginName(userLoginDTO.getLogin_name());
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户名不存在");
        }
        String md5Password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes(StandardCharsets.UTF_8));
        if (!Objects.equals(md5Password, sysUser.getPassword())) {
            throw new RuntimeException("登录密码输入错误");
        }
        sysUser.setLoginIp(ipUtils.getClientIp());
        sysUser.setLoginDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());
        sysUserMapper.updateUser(sysUser);

        //用户名和密码都成功 , 返回一个token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("USER_ID", sysUser.getId());
        //返回
        return new UserLoginVO(JwtUtils.generateJwt(claims));
    }
}
